from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
import sys
import os
os.chdir(os.path.dirname(__file__))


class QListViewDemo(QWidget):
    """
    QListView演示类 - 展示QListView的各种功能和MVC设计模式
    功能包括：增删改查、选择操作、上下文菜单、视图配置等
    """
    addCount = 0  # 添加操作计数器
    insertCount = 0  # 插入操作计数器

    def __init__(self, parent=None):
        super(QListViewDemo, self).__init__(parent)
        self.setWindowTitle("QListView案例")
        # 创建文本编辑框用于显示操作信息
        self.text = QPlainTextEdit('用来显示QListView相关信息：')
        # 创建QListView列表视图
        self.listView = QListView()
        # 创建QStringListModel数据模型，初始化包含6个字符串的列表
        self.model = QStringListModel(['row'+str(i) for i in range(6)])
        # self.model.setStringList(['row'+str(i) for i in range(6)])  # 另一种设置数据的方式
        self.listView.setModel(self.model)  # 将数据模型设置到列表视图

        # 作为对照组 - 创建第二个QListView，共享同一个数据模型
        self.listView2 = QListView()
        self.listView2.setModel(self.model)  # 使用同一个模型，数据同步显示
        self.listView2.setMaximumHeight(80)  # 限制高度以区分显示效果

        # 增删移动操作按钮区域
        self.buttonDelete = QPushButton('删除')    # 删除选中项
        self.buttonAdd = QPushButton('增加')       # 在末尾添加新项
        self.buttonUp = QPushButton('上移')        # 上移选中项
        self.buttonDown = QPushButton('下移')      # 下移选中项
        self.buttonInsert = QPushButton('插入')    # 在选中位置插入新项
        layoutH = QHBoxLayout()
        layoutH.addWidget(self.buttonAdd)
        layoutH.addWidget(self.buttonInsert)
        layoutH.addWidget(self.buttonUp)
        layoutH.addWidget(self.buttonDown)
        layoutH.addWidget(self.buttonDelete)

        # 连接按钮点击信号到对应的槽函数
        self.buttonAdd.clicked.connect(self.onAdd)        # 添加项
        self.buttonInsert.clicked.connect(self.onInsert)   # 插入项
        self.buttonUp.clicked.connect(self.onUp)           # 上移项
        self.buttonDown.clicked.connect(self.onDown)       # 下移项
        self.buttonDelete.clicked.connect(self.onDelete)   # 删除项

        # 选择操作按钮区域
        self.buttonSelectAll = QPushButton('全选')         # 选择所有项
        self.buttonSelectClear = QPushButton('清除选择')    # 清除所有选择
        self.buttonSelectOutput = QPushButton('输出选择')   # 输出选中项信息
        layoutH2 = QHBoxLayout()
        layoutH2.addWidget(self.buttonSelectAll)
        layoutH2.addWidget(self.buttonSelectClear)
        layoutH2.addWidget(self.buttonSelectOutput)
        # 连接选择操作按钮信号到对应的槽函数
        self.buttonSelectAll.clicked.connect(self.onSelectAll)        # 全选
        self.buttonSelectClear.clicked.connect(self.onSelectClear)    # 清除选择
        self.buttonSelectOutput.clicked.connect(self.onSelectOutput)  # 输出选择

        # 主布局设置 - 使用垂直布局管理器
        layout = QVBoxLayout(self)
        layout.addWidget(self.listView)    # 添加主列表视图
        layout.addLayout(layoutH)          # 添加操作按钮布局
        layout.addLayout(layoutH2)         # 添加选择操作按钮布局
        layout.addWidget(self.text)        # 添加信息显示文本框
        layout.addWidget(self.listView2)   # 添加对照列表视图
        self.setLayout(layout)

        # 选择模式设置
        # self.listWidget.setSelectionMode(QAbstractItemView.SingleSelection)  # 单选模式
        self.listView.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 扩展选择模式（支持Ctrl多选）
        self.listView.setSelectionBehavior(QAbstractItemView.SelectRows)     # 按行选择行为

        # 上下文菜单设置
        self.menu = self.generateMenu()  # 生成上下文菜单
        self.listView.setContextMenuPolicy(Qt.CustomContextMenu)  # 允许右键产生自定义菜单
        self.listView.customContextMenuRequested.connect(self.showMenu)  # 连接右键菜单请求信号

        # 列表视图布局属性设置
        self.listView.setResizeMode(self.listView.Adjust)        # 调整大小模式
        self.listView.setLayoutMode(self.listView.Batched)       # 批量布局模式
        self.listView.setMovement(self.listView.Snap)            # 项移动时的吸附效果
        self.listView.setUniformItemSizes(True)                  # 统一项大小
        self.listView.setGridSize(QSize(10,20))                  # 网格大小

        # 第二个视图的不同显示模式设置
        self.listView2.setViewMode(self.listView.IconMode)       # 图标显示模式
        self.listView2.setSpacing(1)                            # 项间距
        self.listView2.setFlow(self.listView2.LeftToRight)       # 从左到右流动布局
        self.listView2.setIconSize(QSize(2,3))                   # 图标大小


    def generateMenu(self):
        menu = QMenu(self)
        menu.addAction('增加',self.onAdd,QKeySequence(Qt.CTRL|Qt.Key_N))
        menu.addAction('插入',self.onInsert,QKeySequence(Qt.CTRL|Qt.Key_I))
        menu.addAction(QIcon("images/close.png"),'删除',self.onDelete,QKeySequence(Qt.CTRL|Qt.Key_D))
        menu.addSeparator()
        menu.addAction('全选',self.onSelectAll,QKeySequence(Qt.CTRL|Qt.Key_A))
        menu.addAction('清空选择',self.onSelectClear,QKeySequence(Qt.CTRL|Qt.Key_R))
        menu.addAction('输出选择',self.onSelectOutput)
        menu.addSeparator()
        # menu.addAction(self.actionHelp)
        return menu

    def showMenu(self, pos):
        self.menu.exec(QCursor.pos())  # 显示菜单

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction('选项1')
        menu.addAction('选项2')
        menu.addAction('选项3')
        menu.exec(event.globalPos())

    def onAdd(self):
        self.addCount += 1
        text = f'新增-{self.addCount}'
        num = self.model.rowCount()
        self.model.insertRow(num)
        index = self.model.index(num)
        self.model.setData(index,text)
        self.text.appendPlainText(f'新增item:"{text}"')

    def onInsert(self):
        self.insertCount += 1
        index = self.listView.currentIndex()
        row = index.row()
        text = f'插入-{self.insertCount}'
        self.model.insertRow(row)
        self.model.setData(index,text)
        self.text.appendPlainText(f'row:{row},新增item:"{text}"')

    def onUp(self):
        index = self.listView.currentIndex()
        row = index.row()
        if row>0:
            self.model.moveRow(QModelIndex(),row,QModelIndex(),row-1)

    def onDown(self):
        index = self.listView.currentIndex()
        row = index.row()
        if row<=self.model.rowCount()-1:
            self.model.moveRow(QModelIndex(),row+1,QModelIndex(),row)


    def onDelete(self):
        index = self.listView.currentIndex()
        text = self.model.data(index)
        row = index.row()
        self.model.removeRow(row)
        self.text.appendPlainText(f'row:{row},删除item:"{text}"')

    def onSelectAll(self):
        self.listView.selectAll()

    def onSelectClear(self):
        self.listView.clearSelection()

    def onSelectOutput(self):
        indexList = self.listView.selectedIndexes()
        for index in indexList:
            row = index.row()
            data = self.model.data(index)
            self.text.appendPlainText(f'row:{row},data:{data}')




if __name__ == "__main__":
    app = QApplication(sys.argv)
    demo = QListViewDemo()
    demo.show()
    sys.exit(app.exec())















